from django.conf import settings
from django.shortcuts import render
from django.template.loader import get_template
from django.template import Context, RequestContext
from django.http import Http404, HttpResponse
from models import Nfdata, UdpEntries, TapsList, TrwList
from django.views.decorators.csrf import csrf_exempt
from django.db import models
import time
from datetime import datetime


dat = getattr(settings, "DAT", None)
yr = int(dat[0:4])
mnth = int(dat[5:7])
da = int(dat[8:10])
c = time.strptime(dat,"%Y-%m-%d %H:%M:%S")
t1 = datetime.strptime(dat,"%Y-%m-%d %H:%M:%S") #current time in datetime format
t = time.mktime(c)
t_now = t
t3 = t - 900 #15 minutes is 900 secs
t2 = t_now - 3600
t2 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(t2))
t2 = datetime.strptime(t2,"%Y-%m-%d %H:%M:%S")   #time before 1 hour in datetime format
t3 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(t3)) 
t3 = datetime.strptime(t3,"%Y-%m-%d %H:%M:%S")  #time before 15 minutes in datetime format

@csrf_exempt
def dash_board(request):
    global t3
    global t1
    #filter data in the time interval flow_time 15 min
    slist1 = Nfdata.objects.filter(flow_time__gte=t3,flow_time__lte=t1).values('dstip').annotate(type_count=models.Count("dstip")).order_by("-type_count")
    slist2 = Nfdata.objects.filter(flow_time__gte=t3,flow_time__lte=t1).values('srcip').annotate(type_count=models.Count("srcip")).order_by("-type_count")
    t = get_template('dash/base.html')
    html = t.render(Context({'slist1':slist1, 'slist2':slist2}))
    return HttpResponse(html)


@csrf_exempt
def top_in_traffic(request):
    slist3 = []
    global t3
    global t1
    global t2
    dst = request.GET.get('srci')
    print dst
    if dst=='1':
	  #filter data in the time interval flow_time 15 min
          slist3 = Nfdata.objects.filter(flow_time__gte=t3,flow_time__lte=t1)
          slist3 = slist3.annotate(tot_bytes=models.Sum("bytes")).values('dstip','tot_bytes')
    if dst=='2':
          #filter data in the time interval flow_time hour
          slist3 = Nfdata.objects.filter(flow_time__gte=t2,flow_time__lte=t1)
          slist3 = slist3.annotate(tot_bytes=models.Sum("bytes")).values('dstip','tot_bytes')
    if dst=='3':
	  #filter data in the time interval flow_time day
          slist3 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth, flow_time__day=da).annotate(tot_bytes=models.Sum("bytes")).values('dstip','tot_bytes')
    if dst=='4':
	  #filter data in the time interval flow_time month
          slist3 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth).annotate(tot_bytes=models.Sum("bytes")).values('dstip','tot_bytes')
   
    slist3 = slist3.annotate(type_count=models.Count("dstip")).order_by("-type_count")
    slist3 = slist3[:10]
    t = get_template('dash/top_in_traffic.html')
    html = t.render(Context({'slist3':slist3}))
    return HttpResponse(html)

def top_out_traffic(request):
    slist4 = []
    global t3
    global t1
    global t2
    dst = request.GET.get('srci')
    print dst
    if dst=='1':
	  #filter data in the time interval flow_time 15 min
          slist4 = Nfdata.objects.filter(flow_time__gte=t3,flow_time__lte=t1)
          slist4 = slist4.annotate(tot_bytes=models.Sum("bytes")).values('srcip','tot_bytes')
          
    if dst=='2':
	  #filter data in the time interval flow_time hour
          slist4 = Nfdata.objects.filter(flow_time__gte=t2,flow_time__lte=t1)
          slist4 = slist4.annotate(tot_bytes=models.Sum("bytes")).values('srcip','tot_bytes')
    if dst=='3':
    	  #filter data in the time interval flow_time day
          slist4 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth, flow_time__day=da).annotate(tot_bytes=models.Sum("bytes")).values('srcip','tot_bytes')
    if dst=='4':
          #filter data in the time interval flow_time month
          slist4 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth).annotate(tot_bytes=models.Sum("bytes")).values('srcip','tot_bytes')
   
    slist4 = slist4.annotate(type_count=models.Count("srcip")).order_by("-type_count")
    slist4 = slist4[:10]
    t = get_template('dash/top_out_traffic.html')
    html = t.render(Context({'slist4':slist4}))
    return HttpResponse(html)

@csrf_exempt
def time_based_plot(request):
    slist5 = []
    slist6 = []
    global t3
    global t1
    global t2
    src = request.POST.get('srcip')
   
    print src
    if src=='1':
        #filter data in the time interval flow_time 15 min
        slist5 = Nfdata.objects.filter(flow_time__gte=t3,flow_time__lte=t1)
    if src=='2':
        #filter data in the time interval flow_time hour
        slist5 = Nfdata.objects.filter(flow_time__gte=t2,flow_time__lte=t1)
    if src=='3':
        #filter data in the time interval flow_time day
        slist5 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth, flow_time__day=da)
    if src=='4':
        #filter data in the time interval flow_time month
        slist5 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth)
    
    t = get_template('dash/time_based_plot.html')
    html = t.render(Context({'slist5':slist5}))
    return HttpResponse(html)

@csrf_exempt
def protocol_based_plot(request):
    slist6 = []
    src = request.POST.get('srcip')
    dst = request.POST.get('dstip')
    byt = request.POST.get('bytes')
    if dst=='1':
       #filter data in the time interval flow_time 15 min
       slist6 = Nfdata.objects.filter(flow_time__gte=t3,flow_time__lte=t1)
    if dst=='2':
       #filter data in the time interval flow_time hour
       slist6 = Nfdata.objects.filter(flow_time__gte=t2,flow_time__lte=t1)
    if dst=='3':
       #filter data in the time interval flow_time day
       slist6 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth, flow_time__day=da)
    if dst=='4':
       #filter data in the time interval flow_time month
       slist6 = Nfdata.objects.filter(flow_time__year=yr, flow_time__month=mnth)
    else:
       slist6 = Nfdata.objects.filter(flow_time__gte=t3,flow_time__lte=t1)
    t = get_template('dash/protocol_based_plot.html')
    html = t.render(Context({'slist6':slist6}))
    return HttpResponse(html)

   
@csrf_exempt
def drawgraph_per_ip(request):
    slist = []
    slist1 = []
    src = request.POST.get('sip')
    slist = Nfdata.objects.filter()
    slist1 = Nfdata.objects.filter()
    #search for IP in and out traffic 
    if src:
       slist = slist.filter(srcip=src)
       slist1 = slist1.filter(dstip=src)
    
    t = get_template('dash/drawgraph_per_ip.html')
    html = t.render(Context({'slist':slist,'slist1':slist1}))
    return HttpResponse(html)

@csrf_exempt
def drawgraph_per_date(request):
    slist = []
    src = request.POST.get('sip')
    sdat = request.POST.get('sdate')
    edat = request.POST.get('edate')
    #search IP in the date interval given in user input 
    #if IP not given filter data in the interval
    slist = Nfdata.objects.filter()
    if src:
	slist = slist.filter(srcip=src)
    if sdat:
	sdt_fmt = datetime.strptime(sdat,"%Y-%m-%d %H:%M:%S") 
	slist = slist.filter(flow_time__gte=sdt_fmt)
    if edat:
	edt_fmt = datetime.strptime(edat,"%Y-%m-%d %H:%M:%S")
	slist = slist.filter(flow_time__lte=edt_fmt)
           
    t = get_template('dash/drawgraph_per_date.html')
    html = t.render(Context({'slist':slist}))
    return HttpResponse(html)

@csrf_exempt
def attack_detection(request):
    adat = getattr(settings, "ATTACK_DATE", None)
    ac = time.strptime(adat,"%Y-%m-%d %H:%M:%S")
    at1 = datetime.strptime(adat,"%Y-%m-%d %H:%M:%S") #current time in datetime format
    at = time.mktime(ac)
    at_now = at
    at2 = at_now - 720
    at2 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(at2))
    at2 = datetime.strptime(at2,"%Y-%m-%d %H:%M:%S")   #time before 12 min in datetime format
    #for null and xmas scan
    adat1 = getattr(settings, "ATTACK_DATE1", None)
    ac1 = time.strptime(adat1,"%Y-%m-%d %H:%M:%S")
    at3 = datetime.strptime(adat1,"%Y-%m-%d %H:%M:%S") #current time in datetime format
    at_n = time.mktime(ac1)
    at_now1 = at_n
    at4 = at_now1 - 240
    at4 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(at4))
    at4 = datetime.strptime(at4,"%Y-%m-%d %H:%M:%S")   #time before 12 min in datetime format
    #list for trw algorithm detected attackers
    trw_list = []
    #list for taps algorithm detected attackers
    tap_list = []
    # 99 is the value of n1 i.e. is upper threshold
    trw_list = TrwList.objects.filter()
    tap_list = TapsList.objects.filter(l_ratio__gte=99)
    t_list = []
    atc_list = []
    f_atc = []
    f_list1 = []
    u_list = []
    u_list1 = []
    t_list = Nfdata.objects.filter(flow_time__gte=at2,flow_time__lte=at1)
    u_list = UdpList.objects.filter(udpcount__gte=3)
    u_list1 = UdpEntries.objects.filter()
    u_list1 = u_list1.values('srcip').annotate(type_count=models.Count("srcip")).order_by("-type_count")[:10]

    n_list = Nfdata.objects.filter(flow_time__gte=at4,flow_time__lte=at3).filter(protocol='tcp').filter(flags='0')
    n_list = n_list.values('srcip').annotate(type_count=models.Count("srcip"))

    x_list = Nfdata.objects.filter(flow_time__gte=at4,flow_time__lte=at3).filter(protocol='tcp').filter(flags='41')
    x_list = x_list.values('srcip').annotate(type_count=models.Count("srcip"))
    
    t_list = t_list.filter(protocol = 'tcp')
    f_list = t_list
    f_list = f_list.filter(flags='1').values('srcip')
    f_list1 = f_list.annotate(type_count=models.Count("srcip"))
    
    t_list1 = t_list
    t_list = t_list.annotate(type_count=models.Count("srcip")).order_by("-type_count")
    t_list = t_list.exclude(dstport = '80')
    t_list1 = t_list1.annotate(type_count1=models.Count("srcip")).order_by("-type_count1")
    t_list1 = t_list1.filter(dstport = '80')
    ip_l = []
    for i2 in t_list:
    	for i1 in t_list1:          
                if i1.srcip==i2.srcip:
                    if i2.flags in ['2','22','3','18','20','27']:
			if not (i2.srcip in ip_l):
                                ip_l.append(i2.srcip)
			        atc_list.append(i2)
    atc_list1 = list(set(atc_list))
    t = get_template('dash/attack_detection.html')
    html = t.render(Context({'at_list':atc_list1,'u_list':u_list1,'n_list':n_list,'x_list':x_list,'trw_list':trw_list,'tap_list':tap_list}))
    return HttpResponse(html)


